package com.glory.brepda.activity.mfg;


import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.DefectListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.EDCListBean;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotLists;
import com.glory.brepda.entity.LotactionLists;
import com.glory.brepda.entity.ScrapEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;


public class DSInspectErrorActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvEqpWork)
    TextView tvEqpWork;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.etSliceNum)
    FreeUI_ClearEditText etSliceNum;
    @BindView(R.id.flDefectList)
    FrameLayout flDefectList;
    @BindView(R.id.ivDefectArrow)
    ImageView ivDefectArrow;
    @BindView(R.id.tvDefectCode)
    TextView tvDefectCode;
    @BindView(R.id.rvDefectList)
    RecyclerView rvDefectList;
    @BindView(R.id.tvDefectNum)
    TextView tvDefectNum;
    @BindView(R.id.etSliceLot)
    TextView etSliceLot;
    //    @BindView(R.id.etStorageid)
//    FreeUI_ClearEditText etStorageid;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    private LotInfoEntity lotInfoEntity;
    private List<String> mMaterielList;
    //批次数量
    private String mainqty;
    private long subqty = 0;
    private DefectListAdapter defectListAdapter;
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private FreeUI_GeneralPop defectcodePop;
    private String defectCode = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_rowinspect;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        etLot.requestFocus();

        defectCodeList = new ArrayList<>();
        mMaterielList = new ArrayList<>();
        mMaterielList.add("04001/一分厂线边仓");
        mMaterielList.add("04002/二分厂线边仓");
        mMaterielList.add("04003/三分厂线边仓");
        initRecyclerView(rvDefectList, this);
        defectListAdapter = new DefectListAdapter(null, tvDefectNum,true);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvDefectList.setAdapter(defectListAdapter);

        defectListAdapter.setListener(new DefectListAdapter.onListener() {
            @Override
            public void OnListener(String s, ScrapEntity item) {
                try {
                    item.setMAINQTY(s.toString());

                    item.setMAINQTY(s.toString());
                    item.setSUBQTY(s.toString());
                    ScrapEntity.MainQTY mainQTY = new ScrapEntity.MainQTY(s.toString());
                    List<ScrapEntity.MainQTY> data = new ArrayList<>();
                    data.add(mainQTY);
                    item.setQTYLIST(data);
                    long num = defectListAdapter.Calculation();
                    if (num < 0) {
                        FreeApi_ToastUtils.showFreeToast("不良数量大于批次数量，请重新输入", MyApp.app, false, Toast.LENGTH_LONG);
                        item.setMAINQTY("0");
                        item.setSUBQTY("0");
                        ScrapEntity.MainQTY mainQTY1 = new ScrapEntity.MainQTY("0");
                        List<ScrapEntity.MainQTY> data1 = new ArrayList<>();
                        data.add(mainQTY1);
                        item.setQTYLIST(data1);
                        tvDefectNum.setText("0");
                    } else {
                        tvDefectNum.setText(num + "");
                        if((subqty-num)>0)
                            etSliceNum.setText(String.valueOf(subqty-num));
                    }

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    protected void initData() {

        initEdit(etLot, s -> {
            LotUtils.searchLotInfo(DSInspectErrorActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {

                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotInfoEntity = response;

                    tvLotState.setText(response.getLOT().getSTATE());
                    mainqty = response.getLOT().getMAINQTY();
                    subqty = Integer.parseInt(response.getLOT().getSUBQTY());
                    defectListAdapter.setTotalNum(Integer.parseInt(response.getLOT().getSUBQTY()));
                    tvEqpWork.setText(response.getLOT().getEQUIPMENTID());
                    etSliceNum.setText(response.getLOT().getSUBQTY());
                    etSliceLot.setText(response.getLOT().getCUSTOMERLOTID());
                    tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                    getDefectInfo(s);
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });

        });

    }

    private void getDefectInfo(String s) {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getADREFLIST();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists) {
                        defectCodeList.add(code.getKEY() + "/" + code.getDESCRIPTION());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GETDEFECT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCENAME", "ScrapCode_DS");
        map.addProperty("REFERENCETYPE", "USER");
        NetUtils.requestPostNet("IF.ADREFLISTQUERY", "Common", DSInspectErrorActivity.this, map, callback);
    }

    @OnClick({R.id.tvBaseSubmit, R.id.flDefectList, R.id.flPositionList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit02")) {
//                    return;
//                }

                if (getText(etLot).equals("")) {
                    showToast("请先扫描批次信息", false);
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")) {
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

//                if (getText(etStorageid).equals("")) {
//                    showToast("请输入库位", false);
//                    return;
//                }
//                if (tvEqpType.getText().toString().equals("")) {
//                    showToast("请选择仓库号", false);
//                    return;
//                }
//                if (tvLotState.getText().toString().equals("等待作业")) {
//                    showConfirmDialog("批次没有作业，请操作进站功能");
//                    return;
//                }
                String defectNum = tvDefectNum.getText().toString().equals("") ? "0" : tvDefectNum.getText().toString();
                String trackOutNum = getText(etSliceNum).equals("") ? "0" : getText(etSliceNum);
                int defectnum = Integer.parseInt(defectNum) + Integer.parseInt(trackOutNum);

                if (defectnum != subqty) {
                    showToast("Die数量输入不正确", false);
                    return;
                }

                for (ScrapEntity defect : defectListAdapter.getData()) {
                    if (defect.getMAINQTY().equals("") || defect.getMAINQTY().equals("0")){
                        showConfirmDialog("不良数不能为空或0，如果没有请删除");
                        return;
                    }
                }

                lotDAWBTrackOut(this, "Common", getSupportFragmentManager(), "", tvEqpWork.getText().toString(),
                        getText(etLot), defectListAdapter.getData(), null, defectCode, String.valueOf(subqty), lotInfoEntity,
                        tvDefectNum.getText().toString().equals("") ? 0 : Integer.parseInt(tvDefectNum.getText().toString()),
                        "",null, new LotUtils.netCallback() {
                            @Override
                            public void onSuccess(Object response) {
                                etLot.requestFocus();
                                etLot.setText("");
                                tvEqpWork.setText("");
                                tvStep.setText("");
                                tvLotState.setText("");
                                etSliceLot.setText("");
                                etSliceNum.setText("");
                                tvDefectCode.setText("");
                                tvDefectNum.setText("");
                                for (int i = defectListAdapter.getData().size() - 1; i >= 0; i--) {
                                    defectListAdapter.remove(i);
                                }
                                defectListAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onFail(Throwable t) {
                                loadError(t, "Common");
                            }
                        });

                break;
            case R.id.flDefectList:
                if (defectCodeList.size() <= 0) {
                    showToast("未获取到不良代码列表", false);
                    return;
                }

                defectcodePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDefectList.getWidth(), defectCodeList, ivDefectArrow, (codeS, i) -> {
                    tvDefectCode.setText(codeS.split("/")[0]);
                    ScrapEntity scrapEntity = new ScrapEntity();
                    scrapEntity.setACTIONCODE(codeS.split("/")[0]);
                    scrapEntity.setACTIONREASON(codeS.split("/")[1]);
                    scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                    scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                    scrapEntity.setACTIONTYPE("Scrap");
                    scrapEntity.setACTIONTYPE("Scrap");

                    if (defectListAdapter.getData().size() > 0) {
                        if (containCode(scrapEntity)) {
                            defectListAdapter.addData(scrapEntity);
                        }
                    } else {
                        defectListAdapter.addData(scrapEntity);
                    }

                });
                FreeApi_PopUtils.setArrowShow(ivDefectArrow);
                defectcodePop.showAsDropDown(flDefectList, 0, 0);
                break;
            case R.id.flPositionList:
                codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mMaterielList, ivPositionArrow, (codeS, i) -> {
                    tvEqpType.setText(codeS);
                    defectCode = codeS.split("/")[0];
                });
                FreeApi_PopUtils.setArrowShow(ivPositionArrow);
                codePop.showAsDropDown(flPositionList, 0, 0);
                break;
        }

    }

    private boolean containCode(ScrapEntity scrapEntity) {
        for (ScrapEntity bean : defectListAdapter.getData()) {
            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
                showToast("列表中已有当前不良代码!", false);
                return false;
            }
        }
        return true;
    }

    public static void lotDAWBTrackOut(Activity context, String method, FragmentManager fragmentManager, String storageid, String eqpWork, String lotID,
                                       List<ScrapEntity> defectData, List<String> carrierList, String defectCode, String subqty, LotInfoEntity lotInfoEntity,
                                       int defectNum, String trackNum, List<EDCListBean.ListBean> edcList, LotUtils.netCallback callback) {
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.dialog_trackout, null);
        TextView tvLotID = view.findViewById(R.id.tvLotID);
        tvLotID.setText(lotID);
        TextView tvStep = view.findViewById(R.id.tvStep);
        tvStep.setText(lotInfoEntity.getLOT().getSTEPNAME() + "/" + lotInfoEntity.getLOT().getSTEPDESC());
        TextView tvEqpID = view.findViewById(R.id.tvEqpID);
        tvEqpID.setText(eqpWork);
        TextView tvTrackInQTY = view.findViewById(R.id.tvTrackInQTY);
        tvTrackInQTY.setText(subqty);
        TextView tvTrackOutQTY = view.findViewById(R.id.tvTrackOutQTY);
        int mSubqty = Integer.parseInt(subqty);
        tvTrackOutQTY.setText(trackNum.equals("") ? String.valueOf(mSubqty - defectNum) : trackNum);
        TextView tvDefectNum = view.findViewById(R.id.tvDefectNum);
        TextView tvDefect = view.findViewById(R.id.tvDefect);
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        int sumDefect = 0;
        if (defectData != null) {
            for (ScrapEntity entity : defectData) {
                if (!entity.getACTIONREASON().contains("不记录良率")) {
                    sumDefect += Integer.parseInt(entity.getMAINQTY().equals("") ? "0" : entity.getMAINQTY());
                }
            }
        } else {
            sumDefect += 0;
        }

        tvDefectNum.setText(String.valueOf(sumDefect));
        BigDecimal b2 = new BigDecimal(Double.toString(mSubqty));
        BigDecimal b1 = new BigDecimal(Double.toString(Integer.parseInt(tvTrackOutQTY.getText().toString())));
        double v1 = b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP).doubleValue();
        double v2 = v1 * 100;
        tvDefect.setText(v2 + "%");

        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        tvCancel.setOnClickListener(view1 -> {
            freeU_generalFragmentDialog.dismiss();
        });
        tvConfirm.setOnClickListener(v -> {
            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                    (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                    }.getType(), fragmentManager, context) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onSuccess(response);
                    FreeApi_LogUtils.saveErrorMessages(response.toString(),"lotDAWBTrackOut");
                    if (response.body().isSuccess(context, false, fragmentManager)) {
                        String holdstate = response.body().getResponse().getBody().getLOTLIST().get(0).getHOLDSTATE();
                        FreeApi_DialogUtils.getConfirmDialog(context, "确定", holdstate.equals("On") ? "该批次良率超标！" : "出站成功", () -> {
                            if (!method.equals("Common")){
                                context.finish();
                            }else {
                                callback.onSuccess("");
                            }
                        }).show(fragmentManager, "CONFIRM_DIALOG");
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onError(response);
                    FreeApi_LogUtils.saveErrorMessages(response.getException(), "LOTTRACKOUT");
                    FreeApi_ToastUtils.showFreeToast("连接服务器失败", context, false, 0);
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", method.equals("Common") ? "InspectErrorTrackOut" : "DefaultTrackOut");
            map.addProperty("EQUIPMENTID", eqpWork);
            if (method.equals("MULTIDEVICELOTTRACKOUT")){
                map.addProperty("TYPE", "1");
            }
            map.addProperty("CARRIERACTION", "");
            map.addProperty("DURABLE", "");
            map.addProperty("ALLREWORKFLAG", "N");
            map.addProperty("WAREHOUSEID", defectCode);
            map.addProperty("STORAGEID", storageid);
            map.addProperty("SPC2", lotInfoEntity.getPART().getSPEC2());
            List<LotLists> lotList = new ArrayList<>();
            List<LotactionLists> lotactionList = new ArrayList<>();
            LotLists lotList1 = new LotLists(lotID,lotInfoEntity.getLOT().getMAINQTY());
            lotList.add(lotList1);

            if (defectData != null) {
                for (ScrapEntity mDefectData : defectData) {
                    ArrayList<LotactionLists.QTYList> qtyList = new ArrayList<>();
                    LotactionLists.QTYList qtybean = new LotactionLists.QTYList();

                    qtybean.setSUBQTY("0");
                    qtybean.setMAINQTY(mDefectData.getMAINQTY());
                    qtyList.add(qtybean);

                    LotactionLists lotactionLists1 = new LotactionLists();
                    lotactionLists1.setLOTID(lotID);
                    lotactionLists1.setACTIONCODE(mDefectData.getACTIONCODE());
                    lotactionLists1.setACTIONREASON(mDefectData.getACTIONREASON());
                    lotactionLists1.setACTIONTYPE("Scrap");
                    lotactionLists1.setSUBQTY(mDefectData.getSUBQTY());
                    lotactionLists1.setMAINQTY(mDefectData.getMAINQTY());
                    lotactionLists1.setQTYLIST(qtyList);

                    lotactionList.add(lotactionLists1);

                }
            }

            map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
            map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(lotactionList)).getAsJsonArray());
            if (edcList != null){
                map.add("EDCLIST", new JsonParser().parse(new Gson().toJson(edcList)).getAsJsonArray());
            }
            NetUtils.requestPostNet("IF.LOTTRACKOUT", method, context, map, callBack);
            freeU_generalFragmentDialog.dismiss();
        });

        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(fragmentManager, "SUBMIT_DIALOG");
    }
}